<template>
  <div class="app-container">

    <!--模糊查询部分数据-->
    <el-form :inline="true" :model="formInline" class="demo-form-inline" size="mini">
      <el-form-item label="菜单名称">
        <el-input v-model="formInline.menuName" placeholder="请输入菜单名称" clearable />
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="formInline.status" placeholder="菜单状态">
          <el-option label="正常" value="0" />
          <el-option label="停用" value="1" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="onSubmit">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="reset">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
        <el-button
          type="primary"
          plain
          icon="el-icon-sort"
          size="mini"
          @click="toggleExpandAll"
        >展开/折叠</el-button>
      </el-col>
    </el-row>
    <br>
    <!--表格数据-->
    <el-table
      v-if="refreshTable"
      :data="menuList"
      :default-expand-all="isExpandAll"
      style="width: 100%;margin-bottom: 20px;"
      row-key="menuId"
      border
      :tree-props="{children: 'menus'}"
    >
      <el-table-column
        prop="menuName"
        label="菜单名称"
        sortable
        width="150"
        align="center"
      />
      <el-table-column
        prop="icon"
        label="图标"
        sortable
        width="120"
        align="center"
      >
        <template slot-scope="scope">
          <i :class="scope.row.icon" />
        </template>

      </el-table-column>
      <el-table-column
        prop="orderNum"
        label="排序"
        width="120"
        align="center"
      />
      <el-table-column
        prop="perms"
        label="权限标识"
        width="150"
      />
      <el-table-column
        prop="component"
        label="组件路径"
        width="150"
        align="center"
      />
      <el-table-column
        prop="status"
        label="状态"
        width="120"
        align="center"
      >
        <template slot-scope="scope">
          <el-tag :type=" scope.row.status == '0'? '':'warning'">{{ scope.row.status == '0'?'正常':'停用' }}</el-tag>
        </template>


      </el-table-column>

      <el-table-column
        prop="createTime"
        label="创建时间"
        align="center"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding " width="200px">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <!--设置按钮不可继续添加-->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-plus"
            @click="handleAdd(scope.row)"
          >新增</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--增加修改数据表单数据-->
    <!-- 表单对话框 -->
    <el-button type="text" @click="dialogFormVisible = true" />
    <el-dialog :title="this.formTile" :visible.sync="dialogFormVisible">
      <el-form ref="menuForm" :model="menuForm" label-width="80px" :rules="rules" class="demo-ruleForm">
        <el-form-item label="上级菜单" prop="parentId">
          <treeselect
            v-model="menuForm.parentId"
            placeholder="请选择上级菜单"
            :options="menuOptions"
            :normalizer="normalizer"
            :show-count="true"
            @select="selectMenu"
          />
        </el-form-item>
        <el-form-item label="菜单类型">
          <el-radio-group v-model="menuForm.menuType">
            <el-radio
              label="M"
              :disabled="this.disable === 1? true:false"
            >目录</el-radio>
            <el-radio label="C">菜单</el-radio>
            <el-radio label="F">按钮</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item v-if="menuForm.menuType != 'F'" label="菜单图标" prop="icon">
          <e-icon-picker
            v-model="menuForm.icon"
            :z-index="9999"
          />
        </el-form-item>

        <el-form-item label="菜单名称" style="display: inline-block" prop="menuName">
          <el-input v-model="menuForm.menuName" placeholder="请输入菜单名称" style="width: 275px" />
        </el-form-item>

        <el-form-item label="显示排序" style="display: inline-block;margin-left: 25px" prop="orderNum">
          <el-input-number v-model="menuForm.orderNum" style="width: 250px;" controls-position="right" :min="1" :max="20" @change="handleChange" />
        </el-form-item>

        <el-form-item v-if="menuForm.menuType != 'F'" label="路由地址" style="display: inline-block;width:360px" prop="path">
          <template>
            <el-tooltip content="访问的路由地址，如：`user`，如外网地址需内链访问则以`http(s)://`开头" placement="top">
              <i class="el-icon-question" ></i>
              <el-input v-model="menuForm.path" placeholder="请输入路由地址" ></el-input>
            </el-tooltip>
          </template>

        </el-form-item>
        <el-form-item v-if="menuForm.menuType != 'F'" label="是否外链" style="display: inline-block;margin-left: 25px">
          <el-radio v-model="menuForm.isFrame" label="0">是</el-radio>
          <el-radio v-model="menuForm.isFrame" label="1">否</el-radio>
        </el-form-item>

        <el-form-item v-if="menuForm.menuType == 'C'" label="组件路径">
          <template>
            <el-tooltip content="访问的组件路径，如：`system/user/index`，默认在`views`目录下" placement="top">
              <i class="el-icon-question" />
              <el-input v-model="menuForm.component" placeholder="请输入组件路径" />
            </el-tooltip>
          </template>

        </el-form-item>
        <el-form-item v-if="menuForm.menuType != 'M'" label="权限字符" style="display: inline-block ">
          <template>
            <el-tooltip content="控制器中定义的权限字符，如：@PreAuthorize(`@ss.hasPermi('system:user:list')`)" placement="top">
              <i class="el-icon-question" />
              <el-input v-model="menuForm.perms" placeholder="请输入权限标识" style="width: 280px" />
            </el-tooltip>
          </template>
        </el-form-item>
        <el-form-item v-if="menuForm.menuType == 'C'" label="是否缓存" style="display: inline-block;margin-left: 25px">
          <el-radio v-model="menuForm.isCache" label="0">缓存</el-radio>
          <el-radio v-model="menuForm.isCache" label="1">不缓存</el-radio>
        </el-form-item>
        <el-form-item v-if="menuForm.menuType != 'F'" label="显示状态" style="display: inline-block">
          <el-radio v-model="menuForm.visible" label="0">显示</el-radio>
          <el-radio v-model="menuForm.visible" label="1">隐藏</el-radio>
        </el-form-item>
        <el-form-item v-if="menuForm.menuType != 'F'" label="菜单状态" style="display: inline-block;margin-left: 170px">
          <el-radio v-model="menuForm.status" label="0">正常</el-radio>
          <el-radio v-model="menuForm.status" label="1">停用</el-radio>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="save('menuForm')">保存</el-button>
        <el-button type="danger" @click="resetForm('menuForm')">关闭</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import store from '../../../store'

import { parseTime } from '../../../utils'
// 引入treeselect
import Treeselect from '@riophae/vue-treeselect'
// import the styles
import '@riophae/vue-treeselect/dist/vue-treeselect.css'

export default {
  name: 'Index',
  components: { Treeselect },
  data() {
    return {
      disable: '', // 单选框的显示
      /* 当前用户名字*/
      userName: '',
      /* 表单规则*/
      rules: {
        menuName: [
          { required: true, message: '请输入菜单名称', trigger: 'blur' },
          { min: 4, max: 8, message: '长度在4到 8 个字符', trigger: 'blur' }
        ],
        orderNum: [
          { required: true, message: '请输入显示顺序', trigger: 'blur' }
        ],
        path: [
          { required: true, message: '请输入路由地址', trigger: 'blur' }
        ]
      },
      // 重新渲染表格状态
      refreshTable: true,
      // 是否展开，默认全部折叠
      isExpandAll: false,
      loading: false, // 遮罩层
      menuList: [], // 表格数据
      menuForm: {
        menuId: '-1',
        parentId: 0,
        menuName: '',
        orderNum: '',
        path: '',
        component: '',
        isFrame: '1',
        isCache: '0',
        menuType: 'C',
        visible: '0',
        status: '0',
        perms: '',
        icon: '',
        createBy: '',
        updateBy: ''
      },
      dialogFormVisible: false, // 表单隐藏
      menuOptions: [], // 菜单树数据
      formTile: '', // 表单表头
      // 模糊查询表单数据
      formInline: {
        menuName: '',
        status: ''
      }

    }
  },
  created() {
    this.loadMenusList()
  },
  methods: {
    selectMenu(val) {
      console.log('selectMenu', val);
      if (val.menuType == 'C') {
        this.disable = 1
      } else {
        this.disable = 2
      }
    },

    /* 表单显示顺序*/
    handleChange(value) {
      console.log(value)
    },
    // 模糊查询提交按钮
    onSubmit() {
      this.loadMenusList()
    },
    // 模糊查询重置按钮
    reset() {
      this.formInline = {
        menuName: '',
        status: ''
      }
    },

    // 保存按钮
    save(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // 新增
          if (this.menuForm.menuId == -1) {
            // 新增
            console.log(this.menuForm);
            this.menuForm.menuId = '';
            this.axios.post('/sysMenu/menu', this.menuForm
            ).then(result => {
              console.log(result.data);
              if (result.data.data == 'ok') {
                this.$message({
                  message: '添加成功',
                  type: 'success',
                  duration: 2000 // 显示时间, 毫秒。
                });
                this.loadMenusList() // 加载页面
              }
            })
          } else {
            // 修改
            console.log(this.menuForm);
            this.axios.put('/sysMenu/menu', this.menuForm
            ).then(result => {
              console.log(result.data);
              if (result.data.data == 'ok') {
                this.$message({
                  message: '修改成功',
                  type: 'success',
                  duration: 2000 // 显示时间, 毫秒。
                });
                this.loadMenusList() // 加载页面
              }
            })
          }
        }

        this.clear();
        // 关闭表单
        this.dialogFormVisible = false
      })
    },

    // 获取数据（模糊查询）
    loadMenusList() {
      this.loading = true;
      this.axios.get('/sysMenu/menu/',
        {
          params: {
            menuName: this.formInline.menuName,
            status: this.formInline.status
          }
        }).then(result => {
        this.loading = false;
        // 处理后台数据(将后台result.data数据与roleList集合绑定)
        this.menuList = result.data.data;
        this.menuOptions = this.menuList
      })
    },
    // 转换树结构
    normalizer(node) {
      if (node.menus && !node.menus.length) {
        delete node.menus
      }

      if (node.menuName == null) {
        node.menuName = '主目录'
      }
        console.log(node.menuName)
      return {
        id: node.menuId,
        label: node.menuName,
        children: node.menus,
          //判断是否为最底层
        isDisabled: !(node.hasOwnProperty('menus'))
      }
    },

    // 折叠菜单
    toggleExpandAll() {
      this.refreshTable = false;
      this.isExpandAll = !this.isExpandAll;
      this.$nextTick(() => {
        this.refreshTable = true
      })
    },

    // 修改(数据回显)
    handleUpdate(row) {
      this.dialogFormVisible = true
      this.formTile = row.menuType == 'M' ? '修改目录' : (row.menuType == 'C' ? '修改菜单' : '修改按钮')
      this.menuForm.updateBy = this.userName
      this.menuForm = JSON.parse(JSON.stringify(row)) // 将row对象解析后赋值给表单对象
    },

    // 删除
    handleDelete(row) {
      console.log(row);
      this.menuForm.menuId = row.menuId;
      this.$confirm('确定删除' + row.menuName + '这一项数据吗?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.axios.delete('/sysMenu/menu/' + this.menuForm.menuId
        ).then(result => {
          if(result.data.data ==='ok'){
              this.$message({
                  type: 'success',
                  message: '删除成功!'
              })

              // 刷新当前页
              this.loadMenusList()
          }

        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 新增
    handleAdd(row) {
      this.menuForm.menuId == '-1'
      this.dialogFormVisible = true;

      /* 获取当前用户名*/
      const user = store.getters.name;
      this.userName = user;
      this.menuForm.createBy = this.userName;
      this.dialogFormVisible = true;
      if (row.menuType === undefined) {
        this.formTile = '新增菜单'
      } else {
        this.formTile = row.menuType == 'M' ? '新增目录' : (row.menuType == 'C' ? '新增菜单' : '新增按钮')
      }

      // this.menuForm.menuType = row.menuType;
      this.menuForm.parentId = row.menuId
    },

    // 关闭表单
    resetForm(menuForm) {
      // 清空规则
      this.$refs.menuForm.clearValidate();
      this.dialogFormVisible = false;
      this.clear()
    },

    /* 格式化时间*/
    parseTime(time) {
      var date = new Date(time);
      return parseTime(date)
    },
    clear() {
      this.menuForm = {
        menuId: '-1',
        parentId: 0,
        menuName: '',
        orderNum: '',
        path: '',
        component: '',
        isFrame: '1',
        isCache: '0',
        menuType: 'C',
        visible: '0',
        status: '0',
        perms: '',
        icon: '',
        createBy: '',
        updateBy: ''
      };
      this.disable = '';
      this.formTile = '';
    }

  }

}

</script>

<style scoped>

</style>
